﻿using App_Clinique.ClassLibrary.Classes;
using App_Clinique.ClassLibrary.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace App_Clinique
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();

            // chargement des données
            Singleton.Current.Patients = Patient.GetList();
            Singleton.Current.ConsultationsDeLaSemaine = Consultation.GetListOfWeek();

            // news 1
            TitreLabel1.Text = string.Empty;
            DateLabel1.Text = string.Empty;
            TexteRichTextBox1.Text = string.Empty;

            // news 2
            TitreLabel2.Text = string.Empty;
            DateLabel2.Text = string.Empty;
            TexteRichTextBox2.Text = string.Empty;

            // news 3
            TitreLabel3.Text = string.Empty;
            DateLabel3.Text = string.Empty;
            TexteRichTextBox3.Text = string.Empty;
        }

        /****************************************************************************************************
         * Methods
         ***************************************************************************************************/
        void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            InitializeActualitesTabs();
        }

        void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            DownloadWebServiceDatasProgressBar.Value = e.ProgressPercentage;
        }

        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            using (WSclinique._Default wsc = new WSclinique._Default())
            {
                // purge des liste dans le Singleton
                Singleton.Current.Actualites.Clear();
                Singleton.Current.Medicaments.Clear();

                WebServiceMedocsBackgroundWorker.ReportProgress(0);
                System.Threading.Thread.Sleep(500);

                try
                {
                    WSclinique.Actualites[] ActualitesWS = wsc.GetActualites();
                    WSclinique.Medicaments[] MedicamentsWS = wsc.GetMedicaments();

                    // prenons uniquement les 3 dernières actualités
                    ActualitesWS.OrderByDescending(a => a.DateActu).Skip(0).Take(3).ToList().ForEach(actualite =>
                    {
                        Actualite ActualiteDB = new Actualite { ActualiteID = actualite.Id, Titre = actualite.Titre, Texte = actualite.Texte, DateActualite = actualite.DateActu };

                        bool ExisteDeja = (Actualite.Get(actualite.Id) != null);
                        if (!ExisteDeja)
                        {
                            Actualite.Create(ActualiteDB);
                        }

                        Singleton.Current.Actualites.Add(ActualiteDB);
                    });

                    WebServiceMedocsBackgroundWorker.ReportProgress(50);
                    System.Threading.Thread.Sleep(500);

                    MedicamentsWS.ToList().ForEach(medicament =>
                    {
                        Medicament MedicamentDB = new Medicament { MedicamentID = medicament.Id, Code = medicament.Code, Nom = medicament.Nom, Designation = medicament.Designation, CodeBarre = medicament.CodeBarre, Laboratoire = medicament.Laboratoire, Categorie = medicament.Categorie };

                        bool ExisteDeja = (Medicament.Get(medicament.Id) != null);
                        if (!ExisteDeja)
                        {
                            Medicament.Create(MedicamentDB);
                        }

                        Singleton.Current.Medicaments.Add(MedicamentDB);
                    });

                    WebServiceMedocsBackgroundWorker.ReportProgress(100);
                    System.Threading.Thread.Sleep(500);
                }
                catch (Exception error)
                {
                    MessageBox.Show(error.Message);

                    Singleton.Current.Actualites = Actualite.GetList();
                    Singleton.Current.Medicaments = Medicament.GetList();
                }
                
            }
        }

        private void InitializePatientDataGridView()
        {
            try
            {
                PatientDataGridView.AutoGenerateColumns = false;
                PatientDataGridView.DataSource = new BindingList<Patient>(Singleton.Current.Patients);

                PatientDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
                PatientDataGridView.BorderStyle = BorderStyle.Fixed3D;

                PatientDataGridView.Show();
            }
            catch (InvalidCastException e)
            {
                MessageBox.Show(e.Message);
            }
        }

        public void RefreshPatientDataGridView()
        {
            PatientDataGridView.DataSource = Singleton.Current.Patients;
            PatientDataGridView.Refresh();
            PatientDataGridView.Parent.Refresh();
        }

        private void InitializeActualitesTabs()
        {
            try
            {
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");

                // news 1
                if (Singleton.Current.Actualites.Count >= 1)
                {
                    tabPage1.Tag = Singleton.Current.Actualites[0];

                    TitreLabel1.Text = Singleton.Current.Actualites[0].Titre;

                    if (Singleton.Current.Actualites[0].DateActualite.HasValue)
                    {
                        DateLabel1.Text = ((DateTime)Singleton.Current.Actualites[0].DateActualite).ToString("F");
                    }

                    String Texte = Singleton.Current.Actualites[0].Texte;
                    TexteRichTextBox1.Text = Texte;
                    if (Texte.Length >= 500)
                    {
                        TexteRichTextBox1.Text = Texte.Substring(0, 500);
                    }
                }

                // news 2
                if (Singleton.Current.Actualites.Count >= 2)
                {
                    tabPage2.Tag = Singleton.Current.Actualites[1];

                    TitreLabel2.Text = Singleton.Current.Actualites[1].Titre;

                    if (Singleton.Current.Actualites[1].DateActualite.HasValue)
                    {
                        DateLabel2.Text = ((DateTime)Singleton.Current.Actualites[1].DateActualite).ToString("F");
                    }

                    String Texte = Singleton.Current.Actualites[1].Texte;
                    TexteRichTextBox2.Text = Texte;
                    if (Texte.Length >= 500)
                    {
                        TexteRichTextBox3.Text = Texte.Substring(0, 500);
                    }
                }

                // news 3
                if (Singleton.Current.Actualites.Count == 3)
                {
                    tabPage3.Tag = Singleton.Current.Actualites[2];

                    TitreLabel3.Text = Singleton.Current.Actualites[2].Titre;

                    if (Singleton.Current.Actualites[2].DateActualite.HasValue)
                    {
                        DateLabel3.Text = ((DateTime)Singleton.Current.Actualites[2].DateActualite).ToString("F");
                    }

                    String Texte = Singleton.Current.Actualites[2].Texte;
                    TexteRichTextBox3.Text = Texte;
                    if (Texte.Length >= 500)
                    {
                        TexteRichTextBox3.Text = Texte.Substring(0, 500);
                    }
                }
            }
            catch (InvalidCastException e)
            {
                MessageBox.Show(e.Message);
            }
        }

        private void InitializeConsultationDataGridView()
        {
            try
            {
                PatientID.DataSource = Singleton.Current.Patients;
                PatientID.DisplayMember = "NomComplet";
                PatientID.ValueMember = "PatientID";

                ConsultationDataGridView.AutoGenerateColumns = false;
                ConsultationDataGridView.DataSource = Singleton.Current.ConsultationsDeLaSemaine;

                ConsultationDataGridView.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
                ConsultationDataGridView.BorderStyle = BorderStyle.Fixed3D;

                ConsultationDataGridView.Show();
            }
            catch (InvalidCastException e)
            {
                MessageBox.Show(e.Message);
            }
        }

        public void RefreshPlanificationDataGridView()
        {
            Singleton.Current.ConsultationsDeLaSemaine.Clear();
            ConsultationDataGridView.DataSource = Singleton.Current.ConsultationsDeLaSemaine;
            ConsultationDataGridView.Refresh();
            ConsultationDataGridView.Parent.Refresh();
        }

        /****************************************************************************************************
         * Events
         ***************************************************************************************************/
        private void MainForm_Load(object sender, EventArgs e)
        {
            this.Dock = DockStyle.Fill;
            InitializePatientDataGridView();
            InitializeConsultationDataGridView();

            WebServiceMedocsBackgroundWorker = new BackgroundWorker();
            WebServiceMedocsBackgroundWorker.DoWork += bw_DoWork;
            WebServiceMedocsBackgroundWorker.ProgressChanged += bw_ProgressChanged;
            WebServiceMedocsBackgroundWorker.RunWorkerCompleted += bw_RunWorkerCompleted;
            WebServiceMedocsBackgroundWorker.WorkerReportsProgress = true;
            WebServiceMedocsBackgroundWorker.RunWorkerAsync();
        }

        private void AjouterPatientButton_Click(object sender, EventArgs e)
        {
            Singleton.Current.ModeCourant = Singleton.Mode.Nouveau;

            PatientForm EcranPatient = new PatientForm();
            EcranPatient.patientDb = new Patient();
            EcranPatient.ShowDialog();
        }

        private void PatientDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewSelectedRowCollection rows = PatientDataGridView.SelectedRows;
            Singleton.Current.ModeCourant = Singleton.Mode.Consultation;
            PatientForm EcranPatient = new PatientForm();
            EcranPatient.patientDb = (Patient)rows[0].DataBoundItem;
            EcranPatient.ShowDialog();
        }

        private void AjouterConsultationButton_Click(object sender, EventArgs e)
        {
            Singleton.Current.ModeCourant = Singleton.Mode.Nouveau;

            PlanificationForm EcranPlanification = new PlanificationForm();
            EcranPlanification.ConsultationDB = new Consultation();
            EcranPlanification.ShowDialog();
        }

        private void ConsultationDataGridView_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DataGridViewSelectedRowCollection rows = ConsultationDataGridView.SelectedRows;
            Singleton.Current.ModeCourant = Singleton.Mode.Consultation;
            PlanificationForm EcranPlanification = new PlanificationForm();
            EcranPlanification.ConsultationDB = (Consultation)rows[0].DataBoundItem;
            EcranPlanification.ShowDialog();
        }

        private void LireActualite1Button_Click(object sender, EventArgs e)
        {
            if (tabPage1.Tag != null)
            {
                DetailsActualiteForm EcranDetailsActualite = new DetailsActualiteForm();
                EcranDetailsActualite.ActualiteDB = (Actualite)tabPage1.Tag;
                EcranDetailsActualite.ShowDialog();
            }
        }

        private void LireActualite2Button_Click(object sender, EventArgs e)
        {
            if (tabPage2.Tag != null)
            {
                DetailsActualiteForm EcranDetailsActualite = new DetailsActualiteForm();
                EcranDetailsActualite.ActualiteDB = (Actualite)tabPage2.Tag;
                EcranDetailsActualite.ShowDialog();
            }
        }

        private void LireActualite3Button_Click(object sender, EventArgs e)
        {
            if (tabPage3.Tag != null)
            {
                DetailsActualiteForm EcranDetailsActualite = new DetailsActualiteForm();
                EcranDetailsActualite.ActualiteDB = (Actualite)tabPage3.Tag;
                EcranDetailsActualite.ShowDialog();
            }
        }
    }
}
